﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LEE.AspNetCore.Extensions.Swagger
{
    internal class AddHeaderOperationFilter : IOperationFilter
    {
        private readonly List<AddHeaderOption> headers;

        public AddHeaderOperationFilter(List<AddHeaderOption> headers)
        {
            this.headers = headers;
        }

        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor descriptor && headers != null && headers.Count > 0)
            {
                headers.ForEach(header =>
                {
                    if (header.IgnoreaAttributeTypes != null && IsIgnore(descriptor, header.IgnoreaAttributeTypes)) return;
                    if (header.IgnoreaHttpMethods != null && header.IgnoreaHttpMethods.Any(x => x.ToUpper() == context.ApiDescription.HttpMethod.ToUpper())) return;
                    operation.Parameters.Add(new NonBodyParameter()
                    {
                        Name = header.Name,
                        In = "header",//query header body path formData
                        Type = "string",
                        Required = header.Required,//是否必填
                        Description = header.Description
                    });
                });
            }
        }

        private bool IsIgnore(ControllerActionDescriptor actionDescriptor, List<Type> ignoreaAttributeTypes)
        {
            if (actionDescriptor.ControllerTypeInfo.CustomAttributes.Any(x => ignoreaAttributeTypes.Any(ignoreaAttributeType => ignoreaAttributeType.IsAssignableFrom(x.AttributeType)))) return true;
            if (actionDescriptor.MethodInfo.CustomAttributes.Any(x => ignoreaAttributeTypes.Any(ignoreaAttributeType => ignoreaAttributeType.IsAssignableFrom(x.AttributeType)))) return true;
            return false;
        }
    }
}
